/**
@file EasyMutex.cpp

@brief 

@details
Copyright (c) 1998 - 2012 Tencent. All Rights Reserved.

@author		admin(admin@tencent.com)
@version	1.0
@date		2012/09/18

history:
<PRE>
History ID	:	1
Author    	:	admin(admin@tencent.com)
DateTime	:	2012/09/18
Description :	Create
</PRE>
*/

// STANDARD INCLUDES
// SYSTEM INCLUDES
// APPLICATION INCLUDES
#include "EasyMutex.h"
// USING NAMESPACES
// DEFINES
// MACROS
// EXTERNAL FUNCTIONS
// EXTERNAL VARIABLES
// CONSTANTS
// STRUCTS
// TYPEDEFS
// FORWARD DECLARATIONS

BOOL EasyMutexInit(EasyMutexId & mid)
{
#if (defined(WIN32) || defined(WIN64))
	// Note:  Windows Critical sections are recursive in nature and perhaps
	//        this implementation calls for a non-recursive implementation
	//        (since there also exists a RecursiveMutex class).  The effort
	//        to make this non-recursive just doesn't make sense though. (SLG)
	InitializeCriticalSection(&mid);
	return TRUE;
#else
	int  rc = pthread_mutex_init(&mid,0);
	assert( rc == 0 );
	return rc == 0;
#endif
}

void EasyMutexLock(EasyMutexId & mid)
{
#if (defined(WIN32) || defined(WIN64))
	EnterCriticalSection(&mid);
#else
	int  rc = pthread_mutex_lock(&mid);
	assert( rc != EINVAL );
	assert( rc != EDEADLK );
	assert( rc == 0 );
#endif
}

void EasyMutexUnlock(EasyMutexId & mid)
{
#if (defined(WIN32) || defined(WIN64))
	LeaveCriticalSection(&mid);
#else
	int  rc = pthread_mutex_unlock(&mid);
	assert( rc != EINVAL );
	assert( rc != EPERM );
	assert( rc == 0 );
#endif
}

BOOL EasyMutexUninit(EasyMutexId &mid)
{
#if (defined(WIN32) || defined(WIN64))
	DeleteCriticalSection(&mid);
	return 0;
#else
	int  rc = pthread_mutex_destroy(&mid);
	assert( rc != EBUSY );  // currently locked
	assert( rc == 0 );
	return rc == 0;
#endif
}

CEasyMutex::CEasyMutex()
{
	EasyMutexInit(m_mutexId);
}
CEasyMutex::~CEasyMutex()
{
	EasyMutexUninit(m_mutexId);
}

VOID  CEasyMutex::lock()
{
	EasyMutexLock(m_mutexId);
}
VOID  CEasyMutex::unlock()
{
	EasyMutexUnlock(m_mutexId);
}
